package com.neighbor.neighborhooduser.controller;

import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.neighbor.neighborhooduser.pojo.PostComments;
import com.neighbor.neighborhooduser.pojo.Posts;
import com.neighbor.neighborhooduser.pojo.Users;
import com.neighbor.neighborhooduser.pojo.dto.CommentDto;
import com.neighbor.neighborhooduser.service.IPostCommentsService;
import com.neighbor.neighborhooduser.service.IPostsService;
import com.neighbor.neighborhooduser.utils.PageUtils;
import com.neighbor.neighborhooduser.utils.ReOpe;
import com.neighbor.neighborhooduser.utils.ResponseMsg;
import jakarta.servlet.http.HttpServletRequest;
import org.apache.ibatis.annotations.Param;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.net.http.HttpRequest;
import java.util.Date;
import java.util.List;

/**
 * <p>
 * 用户帖子表 前端控制器
 * </p>
 *
 * @author song
 * @since 2025-09-22 09:13:04
 */
@RestController

public class PostsController {

    @Autowired
    private IPostsService postService;
    @Autowired
    private IPostCommentsService postCommentsService;

    @Autowired
    private ReOpe reOpe;


    @GetMapping("/posts/search")
    public ResponseMsg searchPosts(@RequestParam(defaultValue = "1") Integer page,
                                   @RequestParam(defaultValue = "5") Integer pageSize,
                                   String title,
                                   String nickname,HttpServletRequest request) {
        // 1. 参数校验和默认值设置
        // 如果页码或每页大小为空，则设置默认值
        if (page == null || page < 1) {
            page = 1;
        }
        if (pageSize == null || pageSize < 1) {
            pageSize = 10;
        }

        // 2. 调用服务层方法获取分页数据
        IPage<Posts> postsIPage = PageUtils.listToPage(postService.getPosts(page, pageSize, null, title, nickname,request));

        // 3. 封装并返回响应
        return ResponseMsg.getInstance(ResponseMsg.SUCCESS, "成功获取帖子列表", postsIPage);
    }

    /**
     * @param postId 路径变量，帖子ID
     * @return ResponseMsg 包含帖子详情的响应消息，如果找不到则返回失败消息
     * @Description 根据帖子ID获取帖子详情
     */
    @GetMapping("/posts/{postId}")
    public ResponseMsg getPost(@PathVariable Integer postId,HttpServletRequest request) {
        if (postId == null) {
            return ResponseMsg.getInstance(ResponseMsg.PARAMETER_ERROR, "帖子ID不能为空");
        }
        return postService.getPostById(postId,request);
    }

    /**
     * 获取热门、讨论、求助贴
     *
     * @param page
     * @param pageSize
     * @return
     */
    @GetMapping("/posts/getHotPosts")
    public ResponseMsg hotPosts(@RequestParam(defaultValue = "1") Integer page,
                                @RequestParam(defaultValue = "5") Integer pageSize,HttpServletRequest request) {
        return ResponseMsg.getInstance(ResponseMsg.SUCCESS, "热门", postService.getHotPosts(page, pageSize,request));
    }

    @GetMapping("/posts/getHelpPosts")
    public ResponseMsg helpPosts(@RequestParam(defaultValue = "1") Integer page,
                                 @RequestParam(defaultValue = "5") Integer pageSize,HttpServletRequest request) {
        return ResponseMsg.getInstance(ResponseMsg.SUCCESS, "热门", postService.getPosts(page, pageSize, 3, null, null,request));
    }

    @GetMapping("/posts/getDiscussionPosts")
    public ResponseMsg DiscussionPosts(@RequestParam(defaultValue = "1") Integer page,
                                       @RequestParam(defaultValue = "5") Integer pageSize,HttpServletRequest request) {
        return ResponseMsg.getInstance(ResponseMsg.SUCCESS, "热门", postService.getPosts(page, pageSize, 2, null, null,request));
    }

    @PostMapping("/posts/publish")
    public ResponseMsg publishDiscussion(
            String title,
            String content,
            Byte type,
            String images,
            HttpServletRequest request) {

        // 1. 验证token
        ResponseMsg tokenResponse = reOpe.IsToken(request);
        if (tokenResponse.getCode() != ResponseMsg.SUCCESS) {
            return ResponseMsg.getInstance(ResponseMsg.TOKEN_ERROR, "请先登录");
        }

        // 2. 参数验证
        if (title == null || title.trim().isEmpty()) {
            return ResponseMsg.getInstance(ResponseMsg.PARAMETER_ERROR, "标题不能为空");
        }
        if (content == null || content.trim().isEmpty()) {
            return ResponseMsg.getInstance(ResponseMsg.PARAMETER_ERROR, "内容不能为空");
        }

        // 3. 获取当前用户
        Users user = (Users) tokenResponse.getData();



        // 5. 创建帖子对象
        Posts post = new Posts();
        post.setUserId(user.getUserId());
        post.setTitle(title);
        post.setContent(content);
        post.setType(type); // 2表示讨论类型
        post.setImages(images); // 存储为JSON数组字符串
        post.setStatus((byte) 1); // 1表示已审核
        post.setSolveStatus((byte) 2); // 2表示未解决（针对求助帖）
        post.setViewCount(0);
        post.setReplyCount(0);
        post.setLikeCount(0);
        post.setCollectCount(0);
        post.setIsTop((byte) 0); // 0表示不置顶
        post.setCreatedAt(new Date());
        post.setUpdatedAt(new Date());

        // 6. 保存到数据库
        boolean saved = postService.save(post);
        if (!saved) {
            return ResponseMsg.getInstance(400, "发布失败，请稍后重试");
        }

        // 7. 返回成功响应
        return ResponseMsg.getInstance(ResponseMsg.SUCCESS, "发布成功", post);
    }







}
